//
//  MKLyricsTool.m
//  singForYou
//
//  Created by nicolas on 2016/12/14.
//  Copyright © 2016年 nicolas. All rights reserved.
//

#import "MKLyricsTool.h"
#import "NSString+Regular.h"
#import "MKMusicTool.h"
#import "MKLyricsModel.h"

@interface MKLyricsTool ()

@property (strong, nonatomic) MKMusicTool *musicTool;

@end

@implementation MKLyricsTool

- (NSArray<MKLyricsModel *> *)lyricsWithLRUrl:(NSURL *)url {

    if (!url) {
        NSLog(@"不能为空");
        return nil;
    }
    //加载.lrc文件所有的字符串
    NSError *error;
    NSString *allContent = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        NSLog(@"加载lrc文件的字符串时出错");
        return nil;
    }
    
    NSArray<NSString *> *sentenceArray = [allContent componentsSeparatedByString:@"\n"];
    NSMutableArray *tempArray = [NSMutableArray array];
    NSString *pattern = @"\\[\\d\\d:\\d\\d.\\d\\d\\]";
    for (NSString *sentence in sentenceArray) {
        NSArray<NSValue *>*rangeValueArray = [sentence matchesRangeByReularWithPattern:pattern];
        NSValue *lastRangeValue = rangeValueArray.lastObject;
        NSRange lastRange = lastRangeValue.rangeValue;
        NSUInteger contentBeginIndex = lastRange.location+lastRange.length;
        NSString *lyrics = [sentence substringFromIndex:contentBeginIndex];
        
        for (NSValue *rangeValue in rangeValueArray ) {
            NSRange range = rangeValue.rangeValue;
            NSString *time = [sentence substringWithRange:NSMakeRange(range.location+1,range.length-2)];
            NSTimeInterval interval = [self.musicTool timeIntervalWithFormatterTime:time];
            MKLyricsModel *model = [[MKLyricsModel alloc] init];
            model.content = lyrics;
            model.time = interval;
            [tempArray addObject:model];
        }
    }
    //TODO:将数组排序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"time" ascending:YES];
    [tempArray sortUsingDescriptors:@[sortDescriptor]];
    return [tempArray copy];
}

#pragma mark - Getter & Setter

- (MKMusicTool *)musicTool {
    if (_musicTool == nil) {
        _musicTool = [[MKMusicTool alloc] init];
    }
    return _musicTool;
}

@end
